// pages/psi/sell/result/index.js
//获取应用实例
const app = getApp();

var wxCharts = require('../../../../utils/wxcharts.js');
var lineChart = null;

var pieChart = null;

const initFilters = {
  overall: 1,
  sorts: '',
  layout: 0,
};

const noData = [{
  name: '暂无数据',
  data: '1',
}, ];

Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
    lineChartData: [],
    top5Data: [],
    userIdentity: '', // 用户身份

    sorts: '',
    overall: 1,
    show: false,
    minVal: '',
    maxVal: '',
    minSalePriceFocus: false,
    maxSalePriceFocus: false,
    filter: initFilters,
    hasLoaded: false,
    // 传参
    cityText: '',
    shopText: '',
    customer_code: '',
    shop_code: '',
    prd_code: '',
    psi_dist: '',
    loading: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 检验是否登录
    app.checkLogin();
    // 获取身份权限
    this.setData({
      userIdentity: app.globalData.userIdentity
    });

    const {
      customerCode = '', shopCode = '', prdCode = '', sellerCode = '', psiDist = ''
    } = options || {};
    console.log('接收参数:');
    console.log(customerCode);
    console.log(shopCode);
    console.log(prdCode);
    console.log(sellerCode);
    console.log(psiDist);
    this.setData({
        customer_code: customerCode,
        shop_code: shopCode,
        prd_code: prdCode,
        seller_code: sellerCode,
        psi_dist: psiDist,
      },
      () => {
        this.init(true);

        // this.setData({
        //   top5Data: [
        //     {
        //       name: '盐酸拉贝洛尔片',
        //       data: 1,
        //     },
        //     {
        //       name: '二硫化硒洗剂',
        //       data: 2,
        //     },
        //   ],
        // });
      },
    );
  },

  touchHandler: function (e) {
    console.log(lineChart.getCurrentDataIndex(e));
    lineChart.showToolTip(e, {
      // background: '#7cb5ec'
    });
  },
  createSimulationData: function () {
    var categories = [];
    var data = [];

    // 判断是否携带数据
    const lineChartData = this.data.lineChartData;

    if (lineChartData && lineChartData.length > 0) {
      lineChartData.forEach((item) => {
        // if (coupon.status === 'default') {
        categories.push(item.name);
        data.push(item.data);
        // }
      });
    }

    return {
      categories: categories,
      data: data,
    };
  },
  //toHome() {
  getChart() {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }

    var lineChartData = this.data.lineChartData;
    var top5Data = this.data.top5Data;
    console.log('windowWidth:' + windowWidth);
    console.log('开始图表');

    var simulationData = this.createSimulationData();
    if (lineChartData.length > 0) {
      lineChart = new wxCharts({
        canvasId: 'lineCanvas',
        title: {
          name: '近一月销量走势',
          fontSize: 12,
        },
        type: 'line',
        categories: simulationData.categories,
        animation: true,
        background: '#f5f5f5',
        series: [{
            name: '日销售量',
            data: simulationData.data,
            format: function (val, name) {
              return val + '';
            },
          },

          //{
          //    name: '成交量2',
          //    data: [11, 24, 29, 15, null, 21, //32, 23, 45, 21],
          //    format: function (val, name) {
          //       return val.toFixed(2) + '万';
          //    }
          //}--
        ],
        xAxis: {
          disableGrid: true,
        },
        yAxis: {
          title: '近一个月销售走势',
          format: function (val) {
            return val.toFixed(0);
          },
          min: 0,
        },
        width: windowWidth,
        height: 150,
        dataLabel: false,
        dataPointShape: true,
        extra: {
          lineStyle: 'curve',
        },
      });
    }

    if (top5Data.length > 0) {
      console.log(top5Data);
    } else {
      top5Data = [{
        name: '暂无数据',
        data: 1,
      }, ];
    }
    pieChart = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas',
      // title: '当日TOP5',
      title: {
        name: '昨日销量排行（TOP5）',
        fontSize: 12,
      },
      // type: 'pie',
      type: 'ring',
      series: top5Data,
      width: windowWidth,
      height: 300,
      dataLabel: true,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  generalQueryData(reset = false) {
    const {
      filter,
      keywords,
      minVal,
      maxVal,
      cityText,
      shopText,
      customer_code,
      shop_code,
      prd_code
    } = this.data;
    const {
      pageNum,
      pageSize
    } = this;
    const {
      sorts,
      overall
    } = filter;
    const params = {
      sort: 0, // 0 综合，1 价格
      pageNum: 1,
      pageSize: 30,
      keyword: keywords,
    };

    if (sorts) {
      params.sort = 1;
      params.sortType = sorts === 'desc' ? 1 : 0;
    }
    if (overall) {
      params.sort = 0;
    } else {
      params.sort = 1;
    }
    // params.minPrice = minVal ? minVal * 100 : 0;
    // params.maxPrice = maxVal ? maxVal * 100 : undefined;

    params.cityText = cityText ? cityText : undefined;
    params.shopText = shopText ? shopText : undefined;

    params.customer_code = customer_code ? customer_code : undefined;
    params.shop_code = shop_code ? shop_code : undefined;
    params.prd_code = prd_code ? prd_code : undefined;

    if (reset) return params;
    return {
      ...params,
      pageNum: pageNum + 1,
      pageSize,
    };
  },

  getSearchResult(params) {
    console.log('getSearchResult');

    const {
      shop_code,
      prd_code,
      seller_code,
      userIdentity
    } = this.data;
    console.log(shop_code);
    console.log(prd_code);
    console.log(seller_code);
    console.log('用户权限：' + userIdentity);

    return new Promise(function (resolve, reject) {
      wx.request({
        url: 'https://sst.jmit.cn/api_sst/getDataSell.aspx',
        // data: 'shop_code=' + this.data.shop_code + '&prd_code=' + this.data.prd_code,
        data: {
          shop_code: shop_code,
          prd_code: prd_code,
          seller_code: seller_code,
          flag: '1', // 0-查询今天 1-查询昨天
          user_identity: userIdentity, // 用户权限
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        success: (request) => {
          console.log('getDataSell', request.data);
          const res = request.data;
          //app.globalData.userInfo = res.data.data;//
          //var data = JSON.parse(res.data);

          resolve(res);
          // if (res.code == 200) {
          //   this.setData({ produces: res.data });
          // } else {
          // }
        },
        fail(res) {
          console.log(res);
          reject(err);
        },
      });
    });
  },

  async init(reset = true) {
    const {
      loadMoreStatus,
      goodsList = []
    } = this.data;
    const params = this.generalQueryData(reset);
    //if (loadMoreStatus !== 0) return;
    console.log(1);
    this.setData({
      loadMoreStatus: 1,
      loading: true,
    });
    try {
      console.log('init');
      const result = await this.getSearchResult(params);

      const code = result.code;
      const data = result.data;
      const lineChartData = result.lineChartData;
      const top5Data = result.top5Data;

      console.log(4);

      console.log(result);
      if (code === 200) {
        // const { spuList, totalCount = 0 } = data;

        // if (totalCount === 0 && reset) {
        //   this.total = totalCount;
        //   this.setData({
        //     emptyInfo: {
        //       tip: '抱歉，未找到相关商品',
        //     },
        //     hasLoaded: true,
        //     loadMoreStatus: 0,
        //     loading: false,
        //     goodsList: [],
        //   });
        //   return;
        // }

        const _lineChartData = lineChartData;
        const _top5Data = top5Data;
        // _goodsList.forEach((v) => {
        //   v.tags = v.spuTagList.map((u) => u.title);
        //   v.hideKey = { desc: true };
        // });
        //const _loadMoreStatus = _goodsList.length === totalCount ? 2 : 0;
        //this.pageNum = params.pageNum || 1;
        //this.total = totalCount;

        this.setData({
          lineChartData: _lineChartData,
          top5Data: _top5Data,
          //loadMoreStatus: _loadMoreStatus,
        });
        // 图表
        this.getChart();
        // 记录操作
        app.api.log({
          title: '实时查询-查询',
          message: 'success',
        })
      } else {
        this.setData({
          loading: false,
        });
        wx.showToast({
          title: '未找到相关数据，请稍候重试',
        });
        // 记录操作
        app.api.log({
          title: '实时查询-查询',
          message: 'fail',
        })
      }
    } catch (error) {
      this.setData({
        loading: false,
      });
      // 记录操作日志
      app.api.log({
        title: '实时查询-查询',
        message: 'error',
      })
    }
    this.setData({
      hasLoaded: true,
      loading: false,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});